package net.xdclass.video.service.Impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.SneakyThrows;
import net.xdclass.video.Exception.ServiceException;
import net.xdclass.video.common.Result;
import net.xdclass.video.controller.dto.UserPasswordDTO;
import net.xdclass.video.entity.News;
import net.xdclass.video.entity.User;
import net.xdclass.video.entity.UserRole;
import net.xdclass.video.mapper.NewsMapper;
import net.xdclass.video.mapper.UserMapper;
import net.xdclass.video.mapper.UserRoleMapper;
import net.xdclass.video.service.NewsService;
import net.xdclass.video.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;

import java.rmi.ServerException;
import java.util.Random;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @SneakyThrows
    @Override
    public void register(User user) {
        String userName = user.getUserName();
        QueryWrapper<User> objectQueryWrapper = new QueryWrapper<>();
        QueryWrapper<User> queryWrapper = objectQueryWrapper.eq("user_name", userName);
        User userOne = userMapper.selectOne(queryWrapper);
        if (userOne!=null){
            throw new ServiceException("用户已存在");
        }
        String encodePassword = passwordEncoder.encode(user.getPassword());
        UserRole userRole = new UserRole();

        user.setNickName(userName);
        user.setUserName(userName);
        user.setPassword(encodePassword);
        user.setUserType("ROLE_ADMIN");
        userMapper.insert(user);
        String usernameId = userMapper.getUsernameId(userName);
        userRole.setRoleId(1L);
        userRole.setUserId(Long.valueOf(usernameId));
        userRoleMapper.insert(userRole);
    }

    @SneakyThrows
    @Override
    public Result UserRegister(User user) {
        String userName = user.getUserName();
        QueryWrapper<User> objectQueryWrapper = new QueryWrapper<>();
        QueryWrapper<User> queryWrapper = objectQueryWrapper.eq("user_name", userName);
        User userOne = userMapper.selectOne(queryWrapper);
        if (userOne!=null){
            return Result.error(String.valueOf(401),"用户已存在");
        }
        String encodePassword = passwordEncoder.encode(user.getPassword());
        user.setNickName(userName);
        user.setUserName(userName);
        user.setPassword(encodePassword);
        user.setUserType("ROLE_USER");
        userMapper.insert(user);
        return Result.success();
    }
    public void batchRegisterRandomUsers() {
        // 创建随机数生成器
        Random random = new Random();

        // 生成1000个随机用户
        for (int i = 1; i <= 1000; i++) {
            try {
                User user = new User();

                // 生成随机用户名 (格式: user_随机6位数字)
                String randomUsername = "user_" + String.format("%06d", random.nextInt(999999));

                // 生成随机密码 (8位随机字母数字组合)
                String randomPassword = generateRandomPassword(8);

                // 设置用户信息
                user.setUserName(randomUsername);
                user.setPassword(randomPassword);

                // 调用注册方法
                UserRegister(user);

                // 可以添加日志输出注册进度
                System.out.println("成功注册第 " + i + " 个用户: " + randomUsername);

                // 添加短暂延迟，避免过快注册
                Thread.sleep(100);

            } catch (Exception e) {
                System.out.println("注册失败，继续下一个: " + e.getMessage());
                continue;
            }
        }

    }

    // 生成随机密码的辅助方法
    private String generateRandomPassword(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder password = new StringBuilder();
        Random random = new Random();

        for (int i = 0; i < length; i++) {
            int index = random.nextInt(chars.length());
            password.append(chars.charAt(index));
        }

        return password.toString();
    }
    @Override
    public Result updatePassword(UserPasswordDTO userPasswordDTO) {
        // 1. 首先将新密码进行加密
        userPasswordDTO.setNewPassword(passwordEncoder.encode(userPasswordDTO.getNewPassword()));
        // 2. 通过用户名查询数据库中存储的（已加密的）密码
        String password = userMapper.getUsernamePassword(userPasswordDTO.getUsername());
        // 3. 使用BCrypt验证用户输入的旧密码是否正确
        // 比较用户输入的旧密码和数据库中存储的加密密码是否匹配
        boolean isPasswordMatch = BCrypt.checkpw(userPasswordDTO.getPassword(), password);
        // 4. 如果密码匹配
        if (isPasswordMatch) {
            // 5. 更新数据库中的密码
            int update = userMapper.updatePassword(userPasswordDTO);
            // 6. 如果更新失败（影响行数小于1），抛出异常
            if (update < 1) {
                throw new ServiceException("密码错误");
            }
            return Result.success();
        }else{
            return Result.error(String.valueOf(401),"原密码不正确");
        }

    }
}
